package com.sun.dream.fish.controller;

import com.sun.dream.fish.frontmodel.model.DictData;
import com.sun.dream.fish.frontmodel.model.DictItem;
import com.sun.dream.fish.frontmodel.named.I18nEnum;
import com.sun.dream.fish.frontmodel.resources.DSFI18nMessage;
import com.sun.dream.fish.session.DsfThreadLocalHelper;
import com.sun.dream.fish.util.DSFClassScanUtil;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Description: 用于国际化的服务接口
 * Created By ljl on 2023/12/05.
 */
@RestController
public class I18nController {

    @GetMapping("/i18n")
    public Map<String, DictData> getI18n() {
        return getI18nData(DsfThreadLocalHelper.getDSFSession().getLocale());
    }

    private Map<String, DictData> getI18nData(String locale) {
        Set<Class<? extends I18nEnum>> i18nEnums = DSFClassScanUtil.reflections.getSubTypesOf(I18nEnum.class);
        Map<String, DictData> result = new HashMap<>();
        if (CollectionUtils.isEmpty(i18nEnums)) {
            return new HashMap<>();
        }
        i18nEnums.forEach(i18nData -> result.put(i18nData.getSimpleName(),
                toDictMap(i18nData, locale)));
        return result;
    }

    private DictData toDictMap(Class<? extends I18nEnum> i18nData, String locale) {

        DictData dictData = new DictData();
        dictData.setDictItemList(Arrays.stream(i18nData.getEnumConstants()).map(data ->
                new DictItem(DSFI18nMessage.getInstance().getMessageByLocale(data.i18nKey(), locale), data.name(), data.ordinal())
        ).collect(Collectors.toList()));
        dictData.setValueName(DSFI18nMessage.getInstance().getMessageByLocale(i18nData.getSimpleName(), locale));
        return dictData;
    }
}
